# scripts/config_loader.py
import json
import os
from pathlib import Path

class ConfigLoader:
    def __init__(self, config_path, project_root):
        """
        :param config_path: 配置文件路径（相对或绝对）
        :param project_root: 项目根路径（Path 对象或字符串）
        """
        self.project_root = Path(project_root).resolve()

        # 配置文件路径：如果是相对路径，则基于项目根路径
        config_file = Path(config_path)
        if not config_file.is_absolute():
            config_file = self.project_root / config_path

        if not config_file.exists():
            raise FileNotFoundError(f"配置文件未找到: {config_file}")

        with open(config_file, 'r', encoding='utf-8') as f:
            self._config = json.load(f)

    def get_section(self, section: str, resolution: str = "4k"):
        """
        获取某个模块的配置，并将 template_dir 等路径转为绝对路径
        """
        if resolution not in self._config["resolutions"]:
            raise ValueError(f"不支持的分辨率: {resolution}")

        res_config = self._config["resolutions"][resolution]
        if section not in res_config:
            raise KeyError(f"配置中未找到模块: {section} 在分辨率 {resolution} 下")

        # 深拷贝配置
        config = res_config[section].copy()

        # 将 template_dir 转为绝对路径
        if "template_dir" in config:
            rel_path = config["template_dir"]
            abs_path = (self.project_root / rel_path).resolve()
            config["template_dir"] = str(abs_path)  # 转为字符串

        return config